package com.xsky.converter;

import java.sql.Clob;

import org.hibernate.Hibernate;

import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.xsky.common.util.Compresser;

public class XStreamClobConverter implements Converter
{

	/**
	 * 将Clob进行压缩编码生成Base64编码
	 */
	public void marshal(Object obj, HierarchicalStreamWriter writer, MarshallingContext ctx)
	{
		Clob clob = (Clob)obj;
		long position = 1;
		int length;
		try
		{
			length = Integer.parseInt(Long.toString(clob.length()));
			String value = clob.getSubString(position, length);
			writer.setValue(value);
		}
		catch(Exception e)
		{
			throw new RuntimeException(e);
		}
		finally
		{
		}
	}
	/**
	 * 从经过压缩编码的字符串中获取Clob
	 */
	public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext ctx)
	{
		Clob obj = null;
		try
		{
			String str = reader.getValue();
			obj = Hibernate.createClob(str);
		}
		catch(Exception e)
		{
			throw new RuntimeException(e);
		}
		return obj;
	}

	public boolean canConvert(Class cls)
	{
		return cls==Clob.class||Clob.class.isAssignableFrom(cls);
	}

}
